// firstPackage/pages/commissionModule/distributionCommissionSetting/distributionCommissionSetting.js

import { settingHouseDistributionCommission, settingHouseDistributionCommissionDetail } from "../../../../service/commission_service"
import { queryAllPersonInfo } from "../../../../service/user_service"
import debounce from "../../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    formData: {
      totalMoney: "",
      recommendId: "",
      list: [],
    },
    showSinglePop: false,
    personCommissionArr: [
      {
        "taxFee": "",
        "totalMoney": "",
        "type": "",
        "typeName": "",
        "name": "",
        "wxUserId": ""
      }
    ],
    recommendId: null,
    isFill: 0,
    typeIndex: 0,

    searchPersonArr: [

    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      recommendId: options.id,
      isFill: options.isFill,
      'formData.recommendId': options.id,
    })
    if (this.data.isFill == 1) {
      //请求回填数据:
      this.settingHouseDistributionCommissionDetail();
      return;
    }
    if (this.data.isFill == 0) {
      wx.showModal({
        title: '提示',
        content: '分佣请一次性完成，提交分佣后不可更改',
        showCancel: false,
        confirmColor: "#FF0000",
        success(res) {
          if (res.confirm) {

          }
        }
      })

    }

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },

  //总佣金输入绑定
  inputCellChange(e) {
    // console.log("JJLog:e==:" + JSON.stringify(e));
    let detail = e.detail;
    this.setData({
      'formData.totalMoney': detail.value
    })
    if (detail.value) {
      if (!this.checkNumber(detail.value)) {
        wx.showToast({
          title: '总佣金只能为数字',
          icon: "none"
        })
        this.setData({
          'formData.totalMoney': "",
        })
      }
    }

  },

  // 人员信息输入绑定:
  cellInputChange(e) {
    let detail = e.detail;
    let key = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index;
    let item = `personCommissionArr[` + index + `].${key}`;
    this.setData({
      [item]: detail.value,
    })
    if (detail.value && key == "name") {
      this.queryAllPersonInfo(detail.value);
    }
    if ((key == "totalMoney" || key == "taxFee") && detail.value && !this.data.formData.totalMoney) {
      wx.showToast({
        title: '请先输入总佣金',
        icon: "none"
      })
      this.setData({
        [item]: "",
      })
      return;
    }
    // if (key == "totalMoney" && detail.value ) {
    //   wx.showToast({
    //     title: '佣金金额不能大于总佣金',
    //     icon: "none"
    //   })

    //   return;
    // }
    if (detail.value && key == 'totalMoney') {

      if (!this.checkNumber(detail.value)) {
        wx.showToast({
          title: '佣金只能为数字',
          icon: "none"
        })
        this.setData({
          [item]: "",
        })
      }
    }
    if (detail.value && key == 'taxFee') {
      if (!this.checkNumber(detail.value)) {
        wx.showToast({
          title: '税费只能为数字',
          icon: "none"
        })
        this.setData({
          [item]: "",
        })
      }
    }
    // console.log("JJLog:当前数组是:" + JSON.stringify(this.data.personCommissionArr));
  },


  //删除一个分佣人员
  cancelOnePersonAction(e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.personCommissionArr;
    arr.splice(index, 1)
    this.setData({
      personCommissionArr: arr
    })
  },

  //新增一个分佣人员:
  addNewPersonAction() {
    let arr = this.data.personCommissionArr || [];
    console.log("JJLgo:arr:" + arr.length);
    let obj = {
      name: "",
      wxUserId: "",
      totalMoney: "",
      taxFee: "",
      type: "",
    }
    if (arr.length < 1) {
      arr.push(obj);

      this.setData({
        personCommissionArr: arr
      })
      return;
    }
    if (arr && arr.length > 0) {
      let tempObj = arr[arr.length - 1];
      if (tempObj.name && tempObj.wxUserId && tempObj.totalMoney &&
        tempObj.taxFee && tempObj.type
      ) {
        arr.push(obj)
        this.setData({
          personCommissionArr: arr
        })
      } else {
        wx.showToast({
          title: '请先完成上一个分佣人员信息填写',
          icon: "none"
        })
      }

    }
  },

  checkNumber(theObj) {
    var reg = /^[0-9]+.?[0-9]*$/;
    if (reg.test(theObj)) {
      return true;
    }
    return false;
  },

  //选中类型:
  selectTypeAction(e) {
    if (this.data.isFill == 1) {
      return;
    }
    let index = e.currentTarget.dataset.index;
    this.setData({
      typeIndex: index,
      showSinglePop: true,
    })
  },

  //类型选中:
  singlePopSelect(e) {
    // console.log("JJLog:单项选择回调:" + JSON.stringify(e));
    let result = e.detail.result;
    let item = 'personCommissionArr[' + this.data.typeIndex + '].type';
    let item1 = 'personCommissionArr[' + this.data.typeIndex + '].typeName';
    this.setData({
      [item]: result.value,
      [item1]: result.label,
      showSinglePop: false
    })
    console.log("JJLog:" + JSON.stringify(this.data.personCommissionArr));
  },

  singlePopHide() {
    this.setData({
      showSinglePop: false
    })
  },
  //提交分佣设置点击
  submitCommissionSetting() {
    if (!this.data.formData.totalMoney || this.data.formData.totalMoney == 0) {
      wx.showToast({
        title: '请输入总佣金',
        icon: "none"
      })
      return;
    }

    let arr = this.data.personCommissionArr;
    let item = arr[arr.length - 1];
    let isAll = false
    if (item.name && item.wxUserId && item.totalMoney &&
      item.taxFee && item.type
    ) {
      isAll = true
    }
    if (!isAll) {
      wx.showToast({
        title: '请完成所有分佣人员信息填写',
        icon: "none"
      })
      return;
    }

    let totalMoney = 0;
    arr.forEach((i) => {
      totalMoney = totalMoney + i.totalMoney + i.taxFee;
    })
    if (totalMoney > this.data.formData.totalMoney) {
      wx.showToast({
        title: '分佣佣金和税费总额不能大于设定的总佣金',
        icon: "none"
      })
      return
    }
    this.setData({
      'formData.list': this.data.personCommissionArr
    })
    console.log("JJLog:提交数据是:" + JSON.stringify(this.data.formData));
    debounce(this.settingHouseDistributionCommission)

  },

  //设置分佣请求:
  settingHouseDistributionCommission() {
    wx.showLoading();
    settingHouseDistributionCommission(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '设置成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000)
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon: "none"
      })
      console.error("JJLog:settingHouseDistributionCommission", err);
    })
  },

  //查询人员请求:
  queryAllPersonInfo(words) {
    queryAllPersonInfo(words).then(res => {
      console.log("JJLog:查询到的人员是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          searchPersonArr: res.data || []
        })
      }
    }).catch(err => {
      console.error("JJLog:queryAllPersonInfo", err);
    })
  },

  selectPersonAction(e) {
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let item1 = 'personCommissionArr[' + index + '].name';
    let item2 = 'personCommissionArr[' + index + '].wxUserId';
    this.setData({
      [item1]: item.name,
      [item2]: item.wxUserId
    })
  },


  //获取已分配佣金详情
  settingHouseDistributionCommissionDetail() {
    wx.showLoading();
    settingHouseDistributionCommissionDetail(this.data.recommendId).then(res => {
      wx.hideLoading();
      console.log("JJLog:详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          formData: res.data,
          personCommissionArr: res.data.list
        })

      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:settingHouseDistributionCommissionDetail", err);
    })
  },
})